import React, { useState, useEffect } from "react";
import {
  Button,
  Card,
  Form,
  Input,
  Typography,
  Divider,
  Modal,
  Select,
  InputNumber,
  message,
  Radio,
  AutoComplete,
  DatePicker,
} from "antd";
import {
  CloseOutlined,
  MinusCircleOutlined,
  PlusOutlined,
} from "@ant-design/icons";
import { useNavigate } from "react-router-dom";
import Loading from "@/components/Loading/index.tsx";
import EditGoods from "@/components/EditGoods/index.tsx";

import styles from "./index.module.scss";
import { req, formaData } from "@/common/methods";

//日期显示国际化、格式化
import locale from "antd/es/date-picker/locale/zh_CN";
// import dayjs from "dayjs";
import "dayjs/locale/zh-cn";

interface TypeProps {
  method: "in" | "out";
}

let baseData: any = {};

const { Text } = Typography;

let timerForSearch: number | undefined = undefined;

const StorageAdd: React.FC<TypeProps> = (props: TypeProps) => {
  /**
   * hash
   *
   */
  const [hash, setHash] = useState<number>(0);
  const [submitButtonDisabled, setSubmitButtonDisabled] =
    useState<boolean>(false);
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const isIn = props && props.method && props.method === "in";
  const onFinish = (values: any) => {
    setSubmitButtonDisabled(true);
    try {
      if (!values || !values.data || !values.data[0]) {
        Modal.error({
          title: "错误",
          content: <>参数无效，或者您未输入任何清单内容</>,
        });
        setSubmitButtonDisabled(false);
        return;
      }
      if (
        !values.data ||
        !Array.isArray(values.data) ||
        values.data.length === 0
      ) {
        Modal.error({
          title: "错误",
          content: <>清单为空，无法提交数据</>,
          onOk() {
            setSubmitButtonDisabled(false);
          },
          onCancel() {
            setSubmitButtonDisabled(false);
          },
        });
      } else {
        const submitData: any[] = [];
        values.data.forEach((item: any) => {
          submitData.push({
            ...item,
            time: formaData(values.time?.$d || new Date()),
            method: values.method, //isIn?10:20,
            depart: values.depart,
            requ: values.requ,
            empl: values.empl,
            change_count: isIn ? item.change_count : 0 - item.change_count,
          });
        });
        req("/api/storage", { data: JSON.stringify(submitData) }, "post")
          .then((data: any) => {
            data;
            Modal.success({
              title: "提交成功",
              content: <>您的{isIn ? "入" : "出"}库单已提交</>,
              onOk() {
                navigate(`/management/lib/${isIn ? "in" : "out"}_storage`);
              },
            });
            //删除当前的本地存储
            localStorage.setItem(
              `storage_change_data_${isIn ? "in" : "out"}`,
              ""
            );
          })
          .catch((error) => {
            Modal.error({
              title: "操作失败",
              content: <>{"" + error}</>,
            });
            setSubmitButtonDisabled(false);
          });
      }
    } catch (e) {
      Modal.error({ title: "未知错误", content: <>{`未知错误` + e}</> });
    }
  };
  const onFinishFailed = (error: any) => {
    try {
      Modal.error({
        title: "无法提交",
        content: (
          <>
            <div>您的输入有误，请检查:</div>
            <pre style={{ backgroundColor: "lightgray" }}>
              {error.errorFields
                .map((item: any) => item.errors.join("\r\n"))
                .join("\r\n")}
            </pre>
          </>
        ),
      });
    } catch (e) {
      Modal.error({
        title: "无法提交",
        content: <>未知错误</>,
      });
    }
  };
  /**
   * 功能：设置出入库方式和isSup
   *
   */
  const [vMethod, setVMethod] = useState(isIn ? 10 : 20);
  const [isSup, setIsSup] = useState(Math.floor(vMethod / 10) === 1);
  useEffect(() => setIsSup(Math.floor(vMethod / 10) === 1), [vMethod]);

  /**
   * 功能：实现基础数据的读取
   *
   */
  const [loading, setLoading] = useState(true);
  const [allDepartForInput, setAllDepartForInput] = useState([]);
  const reqBaseData = () => {
    setLoading(true);
    req("/api/goods/easy_get")
      .then((data: any) => {
        baseData = { ...data };
        //setLoading(false);
        return req(`/api/${isSup ? "suppliers" : "depart"}/get`);
      })
      .then((data: any) => {
        setAllDepartForInput(
          data.map((item: any) => ({
            ...item,
            value: item.id,
            label: item.local ? `${item.name}(${item.local})` : item.name,
            includes: item.includes ? ("" + item.includes).split(" ") : [],
          }))
        );
      })
      .catch((err) => {
        Modal.error({
          title: "初始化错误",
          content: (
            <>
              无法获取基础数据
              <br />
              {"" + err}
            </>
          ),
        });
      })
      .finally(() => setLoading(false));
  };
  useEffect(() => {
    reqBaseData();
    setRequMembers([]);
  }, [isSup]);

  /**
   * 功能：实现成员的可选择
   *
   */
  const [requMembers, setRequMembers] = useState([]);

  /**
   * 功能：实现物品的搜索
   *
   */
  const [goodsInputData, setGoodsInputData] = useState<any>({});

  const handleGoodsChange = (newValue: any, index: any) => {
    const fieldsValue = form.getFieldsValue();
    if (
      typeof fieldsValue === "object" &&
      fieldsValue &&
      typeof fieldsValue.data === "object" &&
      fieldsValue.data &&
      Array.isArray(fieldsValue.data) &&
      fieldsValue.data[index] &&
      typeof fieldsValue.data[index] === "object" &&
      typeof baseData[newValue] === "object"
    ) {
      //console.log(baseData[newValue]);
      fieldsValue.data[index] = {
        ...fieldsValue.data[index],
        goods_name: "" + baseData[newValue].name,
        goods_specs: "" + baseData[newValue].specs,
        goods_unit: "" + baseData[newValue].unit,
        before_count: baseData[newValue].count,
      };
      setHash(Math.random());
      saveLocal();
      setGoodsInputData(
        fromGoodsInputDataGenerateGoodsInputData(goodsInputData)
      );
      // console.log("change,handleGoodsChange", goodsInputData);
      console.log(fromGoodsInputDataGenerateGoodsInputData(goodsInputData));
    }
  };
  const handleGoodsSearch = (key: any) => (newValue: any) => {
    clearTimeout(timerForSearch);
    timerForSearch = window.setTimeout(() => {
      //console.log("延迟");
      req("/api/goods/get_all", { search: ("" + newValue).trim() }, "get")
        .then((data) => {
          setGoodsInputData({
            ...goodsInputData,
            ["" + key]: (data as any).map((item: any) => ({
              value: item?.id || "",
              label: item?.name || "",
            })),
          });
        })
        .catch((error) => {
          message.error("未获取数据" + error);
        });
      //console.log("change,handleGoodsSearch", goodsInputData);
    }, 500);
  };
  /**
   * 本地存储机制
   *
   */
  const fromGoodsInputDataGenerateGoodsInputData = (goodsInputData: any) => {
    try {
      const resultData = (() => {
        const tempData = { ...goodsInputData };
        // console.log("tempData", tempData);
        const resData = (() => {
          let res: any = {};
          let index = 0;
          for (let item in tempData) {
            res[index] = tempData[item];
            index++;
          }
          return res;
        })();
        // console.log("resData", resData);
        return resData;
      })();
      return resultData;
    } catch (e) {
      alert("系统出现严重错误");
    }
  };
  const saveLocal = () => {
    const fieldsValue = form.getFieldsValue();
    localStorage.setItem(
      `storage_change_data_${isIn ? "in" : "out"}`,
      JSON.stringify({
        form: fieldsValue,
        goodsInputData:
          fromGoodsInputDataGenerateGoodsInputData(goodsInputData),
      })
    );
    console.log(
      "获取",
      fieldsValue,
      JSON.stringify({
        form: fieldsValue,
        goodsInputData:
          fromGoodsInputDataGenerateGoodsInputData(goodsInputData),
      })
    );
  };
  const readLocal = () => {
    const read = localStorage.getItem(
      `storage_change_data_${isIn ? "in" : "out"}`
    );
    if (!read || read === "{}") {
      return "";
    }
    const res = JSON.parse(read);
    return res;
  };
  useEffect(() => {
    try {
      const localData = readLocal();
      if (localData) {
        Modal.confirm({
          title: "上次意外离开",
          content: <>是否读取上次未提交的内容？</>,
          onOk() {
            try {
              setGoodsInputData(localData.goodsInputData);
              form.setFieldsValue(localData.form);
            } catch (e) {
              Modal.error({
                title: "读取失败",
                content: (
                  <>
                    系统出错，无法读取上次未提交的数据
                    <br />
                    <a onClick={() => alert("" + e)}>显示详细信息</a>
                  </>
                ),
              });
            }
            localStorage.setItem(
              `storage_change_data_${isIn ? "in" : "out"}`,
              ""
            );
          },
          onCancel() {
            localStorage.setItem(
              `storage_change_data_${isIn ? "in" : "out"}`,
              ""
            );
          },
        });
      }
    } catch (e) {
      Modal.warning({
        title: "系统出错",
        content: (
          <>
            无法读取上次未提交的数据，您需要重新输入，参考:
            <br />
            <pre
              style={{
                backgroundColor: "lightgray",
                maxWidth: 300,
                overflowX: "scroll",
              }}
            >
              {"" + e}
            </pre>
          </>
        ),
        onOk() {
          localStorage.setItem(
            `storage_change_data_${isIn ? "in" : "out"}`,
            ""
          );
        },
      });
    }
  }, []);
  /**
   * 窗口关闭时时询问
   *
   */
  useEffect(() => {
    const beforeUnload = (event: any) => {
      try {
        event.preventDefault();
      } catch (e) {
        //
      }
      return "您有未保存的数据，是否离开？";
    };
    window.addEventListener("beforeunload", beforeUnload);
    return () => {
      window.removeEventListener("beforeunload", beforeUnload);
    };
  }, []);
  return (
    <>
      {loading ? (
        <Loading />
      ) : (
        <>
          <div className={styles["pkg"]}>
            <Form
              name="form"
              form={form}
              onFinish={onFinish}
              onFinishFailed={onFinishFailed}
              style={{ maxWidth: "100%" }}
              autoComplete="off"
              onFieldsChange={() => {
                //setHash(Math.random());
              }}
              onValuesChange={() => {
                //console.log("valuesChange");
                saveLocal();
              }}
            >
              <Card
                key={hash}
                title={`新增${isIn ? "入" : "出"}库单`}
                extra={
                  <CloseOutlined
                    onClick={() => {
                      //remove(field.name);
                      navigate(
                        `/management/lib/${isIn ? "in" : "out"}_storage`
                      );
                    }}
                  />
                }
              >
                <div className={styles["space-between-pkg"]}>
                  <Form.Item
                    name="method"
                    label={(isIn ? "入" : "出") + "库方式"}
                    rules={[{ required: true, message: "方式不能为空" }]}
                    initialValue={isIn ? 10 : 20}
                  >
                    <Radio.Group
                      value={vMethod}
                      onChange={(e) => {
                        setVMethod(e.target.value);
                        //debugger;
                      }}
                    >
                      <Radio value={10}>{isIn ? "进货" : "退货"}</Radio>
                      <Radio value={20}>{isIn ? "退库" : "领用"}</Radio>
                    </Radio.Group>
                  </Form.Item>
                  <Form.Item
                    name="time"
                    label={`${isIn ? "入库" : "出库"}日期`}
                  >
                    <DatePicker locale={locale} />
                  </Form.Item>
                </div>
                <div className={styles["space-pkg"]}>
                  <Form.Item
                    name="depart"
                    label={isSup ? "供货商" : "部门"}
                    rules={[{ required: true, message: "供货商/部门不能为空" }]}
                  >
                    <Select
                      showSearch
                      placeholder={`选择${isSup ? "供货商" : "部门"}`}
                      optionFilterProp="children"
                      filterOption={(
                        input: string,
                        option: { label: string; value: string } | undefined
                      ) =>
                        (option?.label ?? "")
                          .toLowerCase()
                          .includes(input.toLowerCase())
                      }
                      options={[...allDepartForInput]}
                      onChange={(value) => {
                        setRequMembers(
                          (() => {
                            const find: any = allDepartForInput.find(
                              (item: any) => item?.id === value
                            );
                            if (
                              !find ||
                              !find.includes ||
                              !Array.isArray(find.includes)
                            ) {
                              return [];
                            } else {
                              return find.includes.map((item1: any) => ({
                                value: "" + item1,
                              }));
                            }
                          })()
                        );
                      }}
                    />
                  </Form.Item>
                  <Form.Item
                    name="requ"
                    label={isSup ? "经手人" : "申请人"}
                    rules={
                      isSup
                        ? []
                        : [{ required: true, message: "申请人/经手人不能为空" }]
                    }
                  >
                    <AutoComplete
                      options={requMembers}
                      onBlur={(e: any) => {
                        const fieldsValue = { ...form.getFieldsValue() };
                        //console.log(fieldsValue);
                        if (!fieldsValue.empl) {
                          fieldsValue.empl = e?.target?.value || "";
                          form.setFieldsValue({ ...fieldsValue });
                        }
                      }}
                    />
                  </Form.Item>{" "}
                  <Form.Item
                    name="empl"
                    label={
                      isSup
                        ? isIn
                          ? "进货人"
                          : "退货人"
                        : isIn
                        ? "交回人"
                        : "领用人"
                    }
                    rules={
                      isSup
                        ? []
                        : [
                            {
                              required: true,
                              message: "进退货人、领用/交回人不能为空",
                            },
                          ]
                    }
                  >
                    <AutoComplete options={requMembers} />
                  </Form.Item>
                </div>
                <Divider orientation="center">清单</Divider>
                <Form.List name="data">
                  {(fields, { add, remove }) => (
                    <>
                      {fields.map(
                        ({ key, name, ...restField }, index: number) => (
                          <div key={key} className={styles["item-pkg"]}>
                            {isSup && isIn && (
                              <>
                                <Button
                                  size="small"
                                  onClick={((k: any) => (e: any) => {
                                    //console.log(k);
                                    e;
                                    const fieldsValue = {
                                      ...form.getFieldsValue(),
                                    };
                                    if (!fieldsValue.data) {
                                      fieldsValue.data = [];
                                    }
                                    if (!fieldsValue.data[index]) {
                                      fieldsValue.data[index] = {};
                                    }
                                    req("/api/category/get")
                                      .then((categoryData: any) => {
                                        Modal.info({
                                          title: "新增物品",
                                          content: (
                                            <>
                                              <EditGoods
                                                ty="create"
                                                defaultData={
                                                  fieldsValue.data[index]
                                                    .goods_name
                                                    ? {
                                                        name: fieldsValue.data[
                                                          index
                                                        ].goods_name,
                                                      }
                                                    : {}
                                                }
                                                dataCategory={categoryData}
                                                doClose={(data: any) => {
                                                  //console.log(data);
                                                  req("/api/goods/easy_get")
                                                    .then(
                                                      (reqBaseData: any) => {
                                                        baseData = {
                                                          ...reqBaseData,
                                                        };
                                                        handleGoodsSearch(k)(
                                                          "" + data[0].name
                                                        );
                                                        handleGoodsChange(
                                                          data[0].name,
                                                          index
                                                        );
                                                        setGoodsInputData({
                                                          ...goodsInputData,
                                                          ["" + key]: [
                                                            {
                                                              value: data[0].id,
                                                              label:
                                                                data[0].name,
                                                            },
                                                          ],
                                                        });
                                                        fieldsValue.data[
                                                          index
                                                        ] = {
                                                          ...fieldsValue.data[
                                                            index
                                                          ],
                                                          goods_id: data[0].id,
                                                          goods_name:
                                                            data[0].name,
                                                          goods_specs:
                                                            data[0].specs,
                                                          goods_unit:
                                                            data[0].unit,
                                                          before_count: Number(
                                                            data[0].count
                                                          ),
                                                        };
                                                      }
                                                    )
                                                    .catch((error) => {
                                                      Modal.error({
                                                        title: "错误",
                                                        content: (
                                                          <>
                                                            无法检索基本的物品信息，操作失败:
                                                            {"" + error}
                                                          </>
                                                        ),
                                                      });
                                                    });
                                                }}
                                              />
                                            </>
                                          ),
                                          footer: null,
                                        });
                                      })
                                      .catch((error) => {
                                        Modal.error({
                                          title: "错误",
                                          content: (
                                            <>
                                              无法获取类别数据，操作失败
                                              {"" + error}
                                            </>
                                          ),
                                        });
                                      });
                                  })(index)}
                                >
                                  新增物品
                                </Button>
                              </>
                            )}
                            <Form.Item
                              {...restField}
                              name={[name, "goods_name"]}
                              label="物品名称"
                              rules={[
                                { required: true, message: "物品名称不能为空" },
                              ]}
                              hidden
                            >
                              <Input />
                            </Form.Item>
                            <Form.Item
                              {...restField}
                              name={[name, "goods_id"]}
                              label={`物品`}
                              rules={[
                                { required: true, message: "物品不能为空" },
                              ]}
                              className={styles["item-goods-id"]}
                            >
                              <Select
                                showSearch
                                placeholder="选择物品"
                                filterOption={() => true}
                                options={
                                  typeof goodsInputData[key] === "object"
                                    ? goodsInputData[key]
                                    : []
                                }
                                onChange={(values) =>
                                  handleGoodsChange(values, index)
                                }
                                onSearch={handleGoodsSearch(key)}
                                defaultActiveFirstOption={false}
                                suffixIcon={null}
                              />
                            </Form.Item>
                            <Form.Item
                              {...restField}
                              name={[name, "goods_specs"]}
                              label="规格"
                              className={styles["item-specs"]}
                            >
                              <Input placeholder="规格" disabled />
                            </Form.Item>
                            <Form.Item
                              {...restField}
                              name={[name, "goods_unit"]}
                              label="单位"
                              className={styles["item-unit"]}
                            >
                              <Input placeholder="单位" disabled />
                            </Form.Item>{" "}
                            <Form.Item
                              {...restField}
                              name={[name, "change_count"]}
                              label="数量"
                              className={styles["item-count"]}
                              rules={[
                                { required: true, message: "数量不能为空" },
                                {
                                  type: "integer",
                                  min: 1,
                                  message: "数量最低为1",
                                },
                                typeof form.getFieldsValue()?.data?.[index]
                                  ?.before_count === "number" && !isIn
                                  ? {
                                      type: "integer",
                                      max: form.getFieldsValue()?.data?.[index]
                                        ?.before_count,
                                      message: "数量不得超出库存",
                                    }
                                  : {
                                      type: "integer",
                                      max: 10000,
                                      message: "数量不得超出10000",
                                    },
                              ]}
                            >
                              <InputNumber
                                placeholder="数量"
                                addonAfter={
                                  <Text type="secondary">
                                    (现存:
                                    {typeof form.getFieldsValue()?.data ===
                                      "object" &&
                                    typeof form.getFieldsValue()?.data[index]
                                      ?.before_count === "number"
                                      ? form.getFieldsValue()?.data[index]
                                          ?.before_count
                                      : "未知"}
                                    )
                                  </Text>
                                }
                              />
                            </Form.Item>
                            <Form.Item
                              {...restField}
                              name={[name, "remark"]}
                              label="备注"
                              className={styles["item-remark"]}
                            >
                              <Input
                                placeholder={`${key}备注${
                                  form.getFieldsValue()?.data &&
                                  typeof form.getFieldsValue()?.data[index]
                                    ?.goods_id === "number"
                                    ? `[${
                                        form.getFieldsValue()?.data[index]
                                          ?.goods_id
                                      }]`
                                    : ""
                                }${
                                  form.getFieldsValue()?.data &&
                                  typeof form.getFieldsValue()?.data[index]
                                    ?.goods_name === "string"
                                    ? `[${
                                        form.getFieldsValue()?.data[index]
                                          ?.goods_name
                                      }]`
                                    : ""
                                }`}
                              />
                            </Form.Item>
                            <MinusCircleOutlined
                              onClick={() => {
                                remove(name);
                                // console.log(name);
                                //这里的name是key
                                setGoodsInputData(
                                  (() => {
                                    const tempData = { ...goodsInputData };
                                    delete tempData[name];
                                    return { ...tempData };
                                  })()
                                );
                              }}
                            />
                          </div>
                        )
                      )}
                      <Form.Item>
                        <Button
                          type="dashed"
                          onClick={() => {
                            const fieldsValue = form.getFieldsValue();
                            let isNoInput = false;
                            if (Array.isArray(fieldsValue.data)) {
                              fieldsValue.data.forEach((item: any) => {
                                if (!item) {
                                  isNoInput = true;
                                } else if (!item.goods_id) {
                                  isNoInput = true;
                                }
                              });
                            }
                            if (isNoInput) {
                              Modal.warning({
                                title: "无法增加新项目",
                                content: (
                                  <>您有暂未输入的项目，请输入之后再增加</>
                                ),
                              });
                              return;
                            }
                            add();
                          }}
                          block
                          icon={<PlusOutlined />}
                        >
                          增加一栏
                        </Button>
                      </Form.Item>
                    </>
                  )}
                </Form.List>
              </Card>
              <Form.Item className={styles["submit-pkg"]}>
                <Button
                  type="primary"
                  htmlType="submit"
                  className={styles["submit-btn"]}
                  disabled={submitButtonDisabled}
                  loading={submitButtonDisabled}
                >
                  提交{isIn ? "入" : "出"}库单
                </Button>
              </Form.Item>
            </Form>
          </div>
        </>
      )}
    </>
  );
};
export default StorageAdd;
